import { createRouter, createWebHistory } from 'vue-router'
import { initDynamicRouter } from '@/router/modules/dynamicRouter'
import { GlobalStore } from '@/store'
import { HOME_URL, LOGIN_URL } from '@/config/config'
import { AuthStore } from '@/store/modules/auth'

// 2. 定义路由配置
const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      title: '登录页'
    }
  },
  {
    path: '/layout',
    name: 'layout',
    component: () => import('@/layouts/index.vue'),
    redirect: HOME_URL,
    children: []
  }
]

// 3. 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes,
  strict: false,
  scrollBehavior: () => ({ left: 0, top: 0 })
})

router.beforeEach(async (to, from, next) => {
  if (to.name === 'login') {
    return next()
  }
  // 4.判断是否有 Token，没有重定向到 login
  const globalStore = GlobalStore()
  if (!globalStore.token) {
    return next({
      path: LOGIN_URL,
      replace: true
    })
  }
  // 5.如果没有菜单列表，就重新请求菜单列表并添加动态路由
  const authStore = AuthStore()
  if (!authStore.authMenuListGet.length) {
    await initDynamicRouter()
    return next({ ...to, replace: true })
  }
  next()
})

// router.afterEach(() => {})

export default router
